/**
 * 
 */
package any.desktop.server;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author keke <keke@codehaus.org>
 * @version
 * @revision $Revision:$
 */
public class CrawlTask {
	private static final Logger	LOG	= LoggerFactory.getLogger(CrawlTask.class);
	private DesktopService	    desktopService;

	public void crawl() {
		if (LOG.isInfoEnabled()) {
			LOG.info("To execute crawl task");
		}
		final long start = System.currentTimeMillis();
		final List<URI> crawlRoots = desktopService.getCrawlRoots();
		for (final URI root : crawlRoots) {
			if (root.getScheme().equals("file")) {
				crawlFile(root);
			} else {
				LOG.warn("Unsupported Scheme :{}", root.getScheme());
			}
		}
		final long end = System.currentTimeMillis();
		if (LOG.isInfoEnabled()) {
			LOG.info("Crawl Task finished cost {}", (end - start));
		}
		try {
			desktopService.crawlComplete();
		} catch (final IOException e) {
			if (LOG.isErrorEnabled()) {
				LOG.error("Unable to close crawl", e);
			}
		}
	}

	public void setDesktopService(final DesktopService desktopService) {
		this.desktopService = desktopService;

	}

	private void crawlFile(final URI root) {
		final File rootFile = new File(root);
		if (rootFile.exists()) {
			crawlFiles(rootFile);
		}
	}

	private void crawlFiles(final File rootFile) {
		if (rootFile.isDirectory()) {
			final File[] files = rootFile.listFiles();
			for (final File file : files) {
				crawlFiles(file);
			}
		} else {
			try {
				desktopService.index(rootFile.toURI());
			} catch (final Throwable e) {
				if (LOG.isErrorEnabled()) {
					LOG.error("Unable to Index " + rootFile, e);
				}
			}
		}
	}
}
